<template>
  <div class="auth-container">
    <div class="auth-box">
      <div v-if="isLogin" class="title">欢迎登录植物栽培学习平台</div>
      <div v-else-if="isForgotPassword" class="title">找回密码</div>
      <div v-else class="title">欢迎注册</div>
      <el-form ref="formRef" :model="data.form" :rules="data.rules">
        <el-form-item v-if="!isLogin && !isForgotPassword" prop="email">
          <el-input :prefix-icon="Message" size="large" v-model="data.form.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item v-if="!isLogin && !isForgotPassword" prop="emailCode">
          <div class="verification-code-container">
            <el-input
                :prefix-icon="Key"
                size="large"
                v-model="data.form.emailCode"
                placeholder="请输入验证码"
                style="flex: 1"
            ></el-input>
            <el-button
                size="large"
                type="primary"
                :disabled="!data.form.email || countdown > 0"
                @click="sendVerificationCode"
                style="margin-left: 10px"
            >
              {{ countdown > 0 ? `${countdown}秒后重试` : "发送验证码" }}
            </el-button>
          </div>
        </el-form-item>
        <el-form-item v-if="isForgotPassword" prop="emailForForgot">
          <el-input :prefix-icon="Message" size="large" v-model="data.form.emailForForgot" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item v-if="isForgotPassword" prop="forgotEmailCode">
          <div class="verification-code-container">
            <el-input
                :prefix-icon="Key"
                size="large"
                v-model="data.form.forgotEmailCode"
                placeholder="请输入验证码"
                style="flex: 1"
            ></el-input>
            <el-button
                size="large"
                type="primary"
                :disabled="!data.form.emailForForgot || forgotCountdown > 0"
                @click="sendForgotPasswordCode"
                style="margin-left: 10px"
            >
              {{ forgotCountdown > 0 ? `${forgotCountdown}秒后重试` : "发送验证码" }}
            </el-button>
          </div>
        </el-form-item>
        <el-form-item v-if="isForgotPassword" prop="newPassword">
          <el-input show-password :prefix-icon="Lock" size="large" v-model="data.form.newPassword" placeholder="请输入新密码"></el-input>
        </el-form-item>
        <el-form-item v-if="isForgotPassword" prop="confirmNewPassword">
          <el-input show-password :prefix-icon="Lock" size="large" v-model="data.form.confirmNewPassword" placeholder="请确认新密码"></el-input>
        </el-form-item>
        <el-form-item v-if="!isForgotPassword" prop="username">
          <el-input :prefix-icon="User" size="large" v-model="data.form.username" placeholder="请输入账号名称"></el-input>
        </el-form-item>
        <el-form-item v-if="!isForgotPassword" prop="password">
          <el-input show-password :prefix-icon="Lock" size="large" v-model="data.form.password" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item v-if="!isForgotPassword && !isLogin" prop="confirmPassword">
          <el-input show-password :prefix-icon="Lock" size="large" v-model="data.form.confirmPassword" placeholder="请确认密码"></el-input>
        </el-form-item>
        <el-form-item v-if="!isForgotPassword" prop="role">
          <el-select size="large" v-model="data.form.role" placeholder="请选择角色">
            <el-option value="USER" label="普通用户"></el-option>
            <el-option value="ADMIN" label="管理员"></el-option>
            <!-- todo 考虑以后引个专家功能 2025/3/11 -->
            <!--            <el-option value="TEACHER" label="教师"></el-option>-->
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button size="large" type="primary" style="width: 100%" @click="handleAction">{{ isForgotPassword ? '重置密码' : (isLogin ? '登录' : '注册') }}</el-button>
        </el-form-item>
        <div v-if="isLogin" class="register-link">
          没有账号？请 <a href="#" @click.prevent="toggleForm">注册</a>
        </div>
        <div v-if="isLogin" class="forgot-password-link">
          忘记密码？请 <a href="#" @click.prevent="toggleForgotPassword">找回密码</a>
        </div>
        <div v-if="isForgotPassword" class="back-to-login-link">
          返回登录？请 <a href="#" @click.prevent="toggleLoginForm">登录</a>
        </div>
        <div v-if="!isLogin && !isForgotPassword" class="login-link">
          已有账号？请 <a href="#" @click.prevent="toggleForm">登录</a>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref } from "vue";
import { User, Lock, Message, Key } from "@element-plus/icons-vue";
import request from "@/utils/request.js";
import { ElMessage } from "element-plus";
import WebSocketService from '@/services/WebSocketService.js';
import {unreadCount} from "@/router/index.js";

let webSocketService;

const validatePass = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请确认密码'));
  } else {
    if (value !== data.form.password) {
      callback(new Error("确认密码跟原密码不一致!"));
    }
    callback();
  }
};

const validateConfirmNewPass = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请确认新密码'));
  } else {
    if (value !== data.form.newPassword) {
      callback(new Error("确认密码跟新密码不一致!"));
    }
    callback();
  }
};

const isLogin = ref(true);
const isForgotPassword = ref(false);

const data = reactive({
  form: {
    email: '',
    username: '',
    password: '',
    confirmPassword: '',
    role: '',
    emailCode: '',
    emailForForgot: '',
    forgotEmailCode: '',
    newPassword: '',
    confirmNewPassword: ''
  },
  rules: {
    email: [
      { required: true, message: '请输入邮箱', trigger: 'submit' },
      { type: 'email', message: '请输入有效的邮箱地址', trigger: 'submit' }
    ],
    username: [
      { required: true, message: '请输入账号', trigger: 'blur' }
    ],
    password: [
      { required: true, message: '请输入密码', trigger: 'blur' }
    ],
    role: [
      { required: true, message: '请选择角色', trigger: 'blur' }
    ],
    confirmPassword: [
      { validator: validatePass, trigger: 'blur' }
    ],
    emailCode: [
      { required: true, message: '请输入验证码', trigger: 'blur' }
    ],
    emailForForgot: [
      { required: true, message: '请输入邮箱', trigger: 'submit' },
      { type: 'email', message: '请输入有效的邮箱地址', trigger: 'submit' }
    ],
    forgotEmailCode: [
      { required: true, message: '请输入验证码', trigger: 'blur' }
    ],
    newPassword: [
      { required: true, message: '请输入新密码', trigger: 'blur' }
    ],
    confirmNewPassword: [
      { validator: validateConfirmNewPass, trigger: 'blur' }
    ]
  }
});

const formRef = ref();
const countdown = ref(0);
const forgotCountdown = ref(0);

const toggleForm = () => {
  isLogin.value = !isLogin.value;
  isForgotPassword.value = false;
  formRef.value.resetFields();
};

const toggleForgotPassword = () => {
  isForgotPassword.value = true;
  isLogin.value = false;
  formRef.value.resetFields();
};

const toggleLoginForm = () => {
  isForgotPassword.value = false;
  isLogin.value = true;
  formRef.value.resetFields();
};

const handleAction = () => {
  formRef.value.validate(valid => {
    if (valid) {
      if (isForgotPassword.value) {
        forgetPassword();
      } else if (isLogin.value) {
        login();
      } else {
        register();
      }
    }
  });
};

const login = () => {
  request.post('/login', data.form).then(res => {
    if (res.code === '200') {
      ElMessage.success('登录成功');
      localStorage.setItem('user', JSON.stringify(res.data));
      setTimeout(() => {
        if ('USER' === res.data.role) {
          location.href = '/front/home';
        } else {
          location.href = '/manager/home';
        }
      }, 500);
    } else {
      ElMessage.error(res.msg);
    }
  });
};

const register = () => {
  request.post('/user/register', data.form).then(res => {
    if (res.code === '200') {
      ElMessage.success('注册成功');
      toggleForm(); // 切换回登录表单
    } else {
      ElMessage.error(res.msg);
    }
  });
};

const sendVerificationCode = () => {
  request.post('/email/sendVerificationCode', null, { params: { email: data.form.email } }).then(res => {
    if (res.code === '200') {
      ElMessage.success('验证码已发送，请注意查收');
      countdown.value = 60; // 设置倒计时为60秒
      const timer = setInterval(() => {
        if (countdown.value > 0) {
          countdown.value--;
        } else {
          clearInterval(timer);
        }
      }, 1000);
    } else {
      ElMessage.error(res.msg);
    }
  });
};

const sendForgotPasswordCode = () => {
  request.post('/email/sendUpdatePasswordCode', null, {params: {email: data.form.emailForForgot}}).then(res => {
    if (res.code === '200') {
      ElMessage.success('验证码已发送，请注意查收');
      forgotCountdown.value = 60; // 设置倒计时为60秒
      const timer = setInterval(() => {
        if (forgotCountdown.value > 0) {
          forgotCountdown.value--;
        } else {
          clearInterval(timer);
        }
      }, 1000);
    } else {
      ElMessage.error(res.msg);
    }
  });
};

const forgetPassword = () => {
  const payload = {
    email: data.form.emailForForgot,
    emailCode: data.form.forgotEmailCode,
    newPassword: data.form.newPassword
  };
  request.post('/user/forgetPassword', payload).then(res => {
    if (res.code === '200') {
      ElMessage.success('密码重置成功');
      toggleLoginForm(); // 切换回登录表单
    } else {
      ElMessage.error(res.msg);
    }
  });
};

</script>

<style scoped>
.auth-container {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-image: url("@/assets/imgs/plant.jpg");
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  backdrop-filter: blur(10px); /* 为背景添加模糊效果 */
}

.auth-box {
  width: 450px; /* 增加表单宽度 */
  padding: 40px;
  border-radius: 8px;
  box-shadow: 0 0 15px rgba(0, 0, 0, 0.2); /* 阴影更柔和 */
  background-color: rgba(255, 255, 255, 0.85); /* 透明度优化 */
}

.title {
  font-weight: bold;
  font-size: 28px;
  text-align: center;
  margin-bottom: 30px;
  color: #1450aa;
}

.el-form-item {
  margin-bottom: 20px; /* 调整表单项间距 */
}

.el-input, .el-select {
  font-size: 16px;
}

.el-button {
  font-size: 18px;
  padding: 12px;
}

.verification-code-container {
  display: flex;
  align-items: center;
}

.register-link, .login-link, .forgot-password-link, .back-to-login-link {
  text-align: right;
  margin-top: 15px;
}

.register-link a, .login-link a, .forgot-password-link a, .back-to-login-link a {
  color: #1450aa;
  text-decoration: none;
}

.register-link a:hover, .login-link a:hover, .forgot-password-link a:hover, .back-to-login-link a:hover {
  text-decoration: underline;
}
</style>



